package com.mdx.tools.place;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

public class PlaceSqlGenerate {
	
	/**
	 * province数组变成sql
	 */
	public static void PlaceToSql(Place place){
		File file = new File(PlaceConstants.PATH + place.getFileName() + PlaceConstants.FILE_SUFFIX);
		BufferedOutputStream outputStream = null;
		try {
			//如果文件不存在创建文件
			if(!file.exists()) {
				file.createNewFile();
			}
			outputStream = new BufferedOutputStream(new FileOutputStream(file));
			String prefix = place.getCodePrefix() + "000";
			for(int i = 1; i <= place.getProvince().length; i++) {
				String sql = PlaceConstants.SQL_MODEL;
				if(i >= 10) {
					prefix = place.getCodePrefix() + "00";
				} 
				sql = sql + "'" + prefix + i + "',";
				sql = sql + "'"+ place.getParentId() +"',";// 父id
				sql = sql + "'"+ prefix + i + "',";// 编码自增
				sql = sql + "'" + place.getProvince()[i-1] + "',";//添加名称
				sql = sql + "'" + place.getLevel() + "',";
				sql = sql + "'" + place.getIsLeaf() + "');\r\n";//文件末尾换行
				outputStream.write(sql.getBytes());
				PlaceConstants.SB.append(sql);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			//关闭流文件
			try {
				if(outputStream != null) {
					outputStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public static void gerateSql() {
		File file = new File(PlaceConstants.PATH + "地区信息" + PlaceConstants.FILE_SUFFIX);
		BufferedOutputStream outputStream = null;
		//如果文件不存在创建文件
		try {
			if(!file.exists()) {
				file.createNewFile();
			}
			outputStream = new BufferedOutputStream(new FileOutputStream(file));
			outputStream.write(PlaceConstants.SB.toString().getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			//关闭流文件
			try {
				if(outputStream != null) {
					outputStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	} 
	
	public static void generateSetCode(String[] arr) {
		if(arr != null && arr.length > 0) {
			for (String str: arr) {
				String setCode = "PROVINCE_SHORT_TO_CHILDREN_NAME.put(";
				setCode = setCode + "\"" + str +"\",PlaceInfoConstants." + str + ");";
				System.out.println(setCode);
			}
		}
	}
	
	public static void generateArrCode(String[] arr) {
		if(arr != null && arr.length > 0) {
			for (String str: arr) {
				String setCode = "public static final String [] ";
				setCode = setCode + str + " = null;";
				System.out.println(setCode);
			}
		}
	}
	
	public static void main(String[] args) {
		//generateArrCode(PlaceConstants.PROVINCE_SHORT);
		for(Place place: PlaceConstants.PLACE_LIST) {
			PlaceToSql(place);
		}
		gerateSql();
	}
	
}
